package io.cici.server.core.instance;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.cici.server.persistence.remote.model.TaskDto;
import io.cici.server.persistence.remote.model.TaskInstanceDto;
import io.cici.server.persistence.remote.repository.JobInfoRepository;
import io.cici.server.persistence.remote.repository.TaskInstanceRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.ExecutionException;

/**
 * 存储 instance 对应的 JobInfo 信息
 */
@Service
@RequiredArgsConstructor
public class TaskMetaDataService implements InitializingBean {

    private static final int CACHE_CONCURRENCY_LEVEL = 16;
    private final JobInfoRepository jobInfoRepository;
    private final TaskInstanceRepository taskInstanceRepository;
    /**
     * 缓存，一旦生成任务实例，其对应的 JobInfo 不应该再改变（即使源数据改变）
     */
    private Cache<Long, TaskDto> instanceId2JobInfoCache;
    @Value("${oms.instance.metadata.cache.size}")
    private int instanceMetadataCacheSize;

    @Override
    public void afterPropertiesSet() throws Exception {
        instanceId2JobInfoCache = CacheBuilder.newBuilder()
                .concurrencyLevel(CACHE_CONCURRENCY_LEVEL)
                .maximumSize(instanceMetadataCacheSize)
                .softValues()
                .build();
    }

    public TaskDto fetchJobInfoByInstanceId(Long instanceId) throws ExecutionException {
        return instanceId2JobInfoCache.get(instanceId, () -> {
            TaskInstanceDto instanceInfo = taskInstanceRepository.findByInstanceId(instanceId);
            if (instanceInfo != null) {
                Optional<TaskDto> jobInfoOpt = jobInfoRepository.findById(instanceInfo.getTaskId());
                return jobInfoOpt.orElseThrow(() -> new IllegalArgumentException("can't find JobInfo by jobId: " + instanceInfo.getTaskId()));
            }
            throw new IllegalArgumentException("can't find Instance by instanceId: " + instanceId);
        });
    }


    public void loadJobInfo(Long instanceId, TaskDto taskDto) {
        instanceId2JobInfoCache.put(instanceId, taskDto);
    }


    public void invalidateJobInfo(Long instanceId) {
        instanceId2JobInfoCache.invalidate(instanceId);
    }

}
